package com.xl.utils.interceptor;

import com.xl.utils.util.JwtUtil;
import com.xl.utils.util.ResultUtil;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.slf4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;

/**
 * @Author xionglin
 * @Classname JwtInterceptor
 * @Description 拦截器
 * @Date 2019/6/19 11:38
 */
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if(uri.contains("login")){
            return true;
        }else{
            HashMap<String, String> headerMaps = new HashMap<>(3);
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = headerNames.nextElement().trim();
                String value = request.getHeader(key).trim();
                headerMaps.put(key, value);
            }
            String token = headerMaps.get("token");
            if(null == token||"".equals(token)){
                response.setHeader("Content-Type","application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(ResultUtil.ResultJsonStr("100","token认证不通过，请重新登录"));
                return false;
            }
            try {
                JwtUtil.verifyToken(token);
            } catch (Exception e) {
                logger.error(e.getMessage());
                response.setHeader("Content-Type","application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(ResultUtil.ResultJsonStr("100","token认证不通过，请重新登录"));
                return false;
            }
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
